#!/bin/bash

sudo mount -rw -o remount /



#install qrencode
if [ ! -f "/usr/bin/qrencode" ]; then
	sudo dpkg --configure -a
	sudo apt update
	sudo echo y | apt-get install qrencode
fi

#install ffmpeg
if [ ! -f "/usr/bin/ffmpeg" ]; then
	sudo dpkg --configure -a
	sudo apt update
	sudo echo y | apt-get install ffmpeg
fi

echo Please make sure the printer is running and connected to this raspberry pi.
echo Do you want to connect the monitor camera to the printer?

#check usb camera connected
video_result=`v4l2-ctl --list-devices -d /dev/video0 | grep usb`
echo $video_result
if [[ $video_result =~ "usb" ]]
then
	echo "Usb camera was connected!"
else
	echo "Usb camera was not connected!"
	until [[ "$input" = y ]] || [[ "$input" = Y ]]
	do
       		echo 'Ignore inserting USB camera? [y/n]:'
       		echo '[y/n]:'
       		read input
       		if [[ "$input" = n ]] || [[ "$input" = N ]]
       		then
           		echo 'Please plug in the USB camera and restart the printer service.'
   	   		exit
       		fi
	done
fi

baseDirForScriptSelf=$(cd "$(dirname "$0")"; pwd)
#echo "full path to currently executed script is : ${baseDirForScriptSelf}"
p2pcfg="$baseDirForScriptSelf/p2pcfg.json"
if [ ! -f "$p2pcfg" ]; then
	sudo echo "
	{	
		 "APILicense" : "123",
		 "DIDString" : "456",
		 "InitString" : "789"
	}" > $p2pcfg
fi

GenerateIdentifier="$baseDirForScriptSelf/GenerateIdentifier"
if [ ! -f "$GenerateIdentifier" ]; then
        echo "$GenerateIdentifier" was not exist!
        exit 0
fi
#connect printer check
printer_couter=0
printer=$(ls -rtl /dev/ | grep "ttyUSB" | grep -v grep | awk '{print $10}')
#echo "$printer"
baudrate_arr=(115200 250000)

if [ -n "$printer" ]; then
        #echo Printer  was not connected, please connect to creality 3D printer from Serial!
        #echo And then restart printer services [ creality_printer.service ]!
        #exit 0
	for baudrate in ${baudrate_arr[@]}
	do
		echo baudrate was $baudrate
		sudo "$GenerateIdentifier" -b $baudrate -p /dev/"$printer" > /dev/null
		return_val=$?
		if [[ $return_val =~ 0 ]]
		then
		#	exit
			echo  The /dev/"$printer" was not printer Serial.
		else
			#$printer_cout=$((${printer_cout} + 1))
			printer_couter=1
			
			echo "$printer":"$baudrate" > printer_serial.txt
			break

		fi
	done
fi
if [[ $printer_couter -eq 0 ]]; then
	echo "3D Printer was not connected, please connected!"
	exit
fi


sudo "$GenerateIdentifier" -a /dev/ttyUSB0 
RETURN=$?
#echo $RETURN
return_val=0

#echo $return_val
if [ "$RETURN" -ne "$return_val" ] 
then
	if [ "$RETURN" = -1 ];then
		echo "Time out, The verification code has expired. Please execute this command again [sudo ./creality_install]  to install the 3D printer service."
		exit
	fi
	if [ "$RETURN" = -2 ];then
		echo "The request for verification code failed. Please check the network  is connected to the Internet."
		exit
	fi
fi	
#echo $RETURN

#3D printer services
sudo echo "[Unit]
Description= creality printer server
After=network.target

[Service]
Restart=on-failure
RestartSec=1
Type=simple
#Type=forking
PIDFile=/run/printer.pid
ExecStart=$baseDirForScriptSelf/creality_start 
ExecStop=$baseDirForScriptSelf/creality_stop

[Install]
WantedBy=multi-user.target" > $baseDirForScriptSelf/creality_printer.service
sudo mv "$baseDirForScriptSelf"/creality_printer.service /usr/lib/systemd/system 

# Video Monitoring services
sudo echo "[Unit]
Description= creality printer server
After=network.target

[Service]
Restart=on-failure
RestartSec=1
Type=simple
#Type=forking
PIDFile=/run/video.pid
ExecStart=$baseDirForScriptSelf/video_start 
ExecStop=$baseDirForScriptSelf/video_stop

[Install]
WantedBy=multi-user.target" > $baseDirForScriptSelf/creality_video_monitoring.service
sudo mv "$baseDirForScriptSelf"/creality_video_monitoring.service /usr/lib/systemd/system 

# uart hotplug
sudo echo "ACTION==\"add\", ATTRS{product}==\"USB Serial\", SUBSYSTEMS==\"usb\", RUN+=\"$baseDirForScriptSelf/usbdrive.sh &\"
ACTION==\"remove\", ATTRS{product}==\"USB Serial\",  SUBSYSTEMS==\"usb\", RUN+=\"$baseDirForScriptSelf/usbdrive.sh &\"" > $baseDirForScriptSelf/98-3d-printer.rules
sudo mv "$baseDirForScriptSelf"/98-3d-printer.rules /etc/udev/rules.d/ 

p2pcfg="$baseDirForScriptSelf/p2pcfg.json"
if [ ! -f "$p2pcfg" ]; then
	sudo echo "
	{	
		 "APILicense" : "123",
		 "DIDString" : "456",
		 "InitString" : "789"
	}" > $p2pcfg
fi
sudo systemctl enable creality_printer.service
sudo systemctl stop creality_printer.service
sudo systemctl start creality_printer.service


sudo systemctl enable creality_video_monitoring.service
sudo systemctl stop creality_video_monitoring.service
sudo systemctl start creality_video_monitoring.service
